import { defineStore } from 'pinia';

export const useMonthHistoryStore = defineStore('monthhistory', () => {
  const monthList = ref<any[]>([]);
  const total = ref<number>(0);
  function filterAndDeduplicate(data: any[]): any[] {
    const uniqueYearMonths = new Set<string>();
    const result: { yearMonth: string }[] = [];
    data.forEach((item) => {
      if (item.yearMonth && !uniqueYearMonths.has(item.yearMonth)) {
        result.push(item);
        uniqueYearMonths.add(item.yearMonth);
      }
    });
    return result;
  }
  function convertYearMonthFormat(data: { yearMonth: string }[]): { yearMonth: string }[] {
    const result: { yearMonth: string }[] = [];
    data.forEach((item) => {
      const year = item.yearMonth.substring(0, 4);
      const month = item.yearMonth.substring(4, 6);
      const newFormat = `${year}年${month}月`;
      result.push({ yearMonth: newFormat });
    });
    return result;
  }
  function sortYearMonthsDescending(data: { yearMonth: string }[]): { yearMonth: string }[] {
    data.sort((a, b) => {
      return b.yearMonth.localeCompare(a.yearMonth);
    });
    return data;
  }
  const getMonthList = async () => {
    const data = ref<any[]>([]);
    await getAllMonthList(1, 100).then((res: any) => {
      total.value = res.data.total;
      data.value = res.data.records;
    });
    if (total.value < data.value.length) {
      const num = Math.trunc(total.value / 100) + 1;
      for (let i = 1; i < num; i++) {
        await getAllMonthList(i, 100).then((res: any) => {
          data.value.push(res.data.records);
        });
      }
    }
    // 处理数据
    const list = ref<any[]>([]);
    for (let i = 0; i < data.value.length; i++) {
      list.value.push({ yearMonth: data.value[i].yearMonth });
    }
    list.value = filterAndDeduplicate(list.value);
    list.value = convertYearMonthFormat(list.value);
    monthList.value = sortYearMonthsDescending(list.value);
  };
  return {
    monthList,
    getMonthList,
  };
});
